package com.ai.dmc.index.web.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.lang3.Validate;

/**
 * zip压缩工具
 * 
 * @see
 * @author Hu
 * @date 2015-3-13 下午1:53:43
 * @version
 * @desc TODO
 */
public class ZipUtil {

	/**
	 * 压缩单个文件为zip
	 * 
	 * @param filepath
	 * @param zipName
	 * @return
	 */
	public static boolean compress(String filePath, String zipPath) {

		filePath = filePath.replace("\\\\", "\\").replace("\\", "/");
		zipPath = zipPath.replace("\\\\", "\\").replace("\\", "/");
		int index = zipPath.lastIndexOf("/");
		String sxffZip = zipPath.substring(filePath.lastIndexOf("."));
		String zipDir = zipPath.substring(0, index);
		File dirFile = new File(zipDir);

		Validate.isTrue(new File(filePath).exists(), "文件路径不存在");
		Validate.isTrue(".zip".equalsIgnoreCase(sxffZip), "zip路径不合法，请输入后缀为.zip的文件路径");
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		// 创建文件输入流对�?
		BufferedInputStream bis = null;
		// 创建ZIP数据输出流对�?
		ZipOutputStream zipOut = null;
		//
		ZipEntry zipEntry = null;

		CheckedOutputStream cos = null;

		String fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
		try {
			cos = new CheckedOutputStream(new FileOutputStream(zipPath), new CRC32());
			zipOut = new ZipOutputStream(cos);
			bis = new BufferedInputStream(new FileInputStream(new File(filePath)));
			zipEntry = new ZipEntry(fileName);

			zipOut.putNextEntry(zipEntry);
			int count;
			byte data[] = new byte[1024];
			while ((count = bis.read(data, 0, 1024)) != -1) {
				zipOut.write(data, 0, count);
			}
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("创建zip文件异常...", e);
		} finally {
			try {
				if (zipOut != null) {
					zipOut.close();
				}
				if (bis != null) {
					bis.close();
				}
				if (cos != null) {
					cos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
